/*
 *  linux/kernel/mktime.c
 *
 *  (C) 1991  Linus Torvalds
 */
// 这不是库函数，仅供内核使用。从1970年1月1日0时起到开机时经过的时间（秒）作为开机时间
#include <time.h>

/*
 * This isn't the library routine, it is only used in the kernel.
 * as such, we don't care about years<1970 etc, but assume everything
 * is ok. Similarly, TZ etc is happily ignored. We just do everything
 * as easily as possible. Let's find something public for the library
 * routines (although I think minix times is public).
 */
/*
 * PS. I hate whoever though up the year 1970 - couldn't they have gotten
 * a leap-year instead? I also hate Gregorius, pope or no. I'm grumpy.
 */
#define MINUTE 60
#define HOUR (60*MINUTE)
#define DAY (24*HOUR)
#define YEAR (365*DAY)

/* interestingly, we assume leap-years */
static int month[12] = {
	0,
	DAY*(31),
	DAY*(31+29),
	DAY*(31+29+31),
	DAY*(31+29+31+30),
	DAY*(31+29+31+30+31),
	DAY*(31+29+31+30+31+30),
	DAY*(31+29+31+30+31+30+31),
	DAY*(31+29+31+30+31+30+31+31),
	DAY*(31+29+31+30+31+30+31+31+30),
	DAY*(31+29+31+30+31+30+31+31+30+31),
	DAY*(31+29+31+30+31+30+31+31+30+31+30)
};

long kernel_mktime(struct tm * tm)//参数tm中各字段已经在init/main.c中被赋值，信息取自CMOS
{
	long res;
	int year;
    // 实际上下面对于闰年的考虑是不完善的。因为每100年要判断是否整除400，只有整除400才是闰年。不过在2100年之前都是无伤大雅。更何况还存在千年虫问题
	year = tm->tm_year - 70;//从1970年到现在经过的年数（2位表示），会有千年虫问题
/* magic offsets (y+1) needed to get leapyears right.*/
	res = YEAR*year + DAY*((year+1)/4); //由于年份从1970年开始计算，因此到1972年就是一个闰年。这样从1970年算起，闰年的计算方法就是1 + (y - 3) /4，即为(y+1)/4
	res += month[tm->tm_mon];
/* and (y+2) here. If it wasn't a leap-year, we have to adjust */
	if (tm->tm_mon>1 && ((year+2)%4)) //如果当年不是闰年，那么我们必须减去一天的秒数
		res -= DAY;
	res += DAY*(tm->tm_mday-1);
	res += HOUR*tm->tm_hour;
	res += MINUTE*tm->tm_min;
	res += tm->tm_sec;
	return res;
}
